<template>
  <view class="nav-box">
    <view class="nav-item" v-for="(item, index) in list" :key="index" @click="changeTab(index)">
      <text class="nav-text" :class="{ 'nav-text-active': index == current }">
        {{ item.label }}
      </text>
    </view>
    <view
      class="nav-line"
      :class="{ 'line-bg': !lineColor, 'nav-line-transition': lockDx }"
      :style="{ left: distance + 'rpx' }"
    ></view>
  </view>
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import type { PropType } from 'vue';
  import type { NavList } from './mt-tab';

  const props = defineProps({
    list: {
      type: Array as PropType<NavList[]>,
      default: 0,
    },
    current: {
      type: Number,
      default: 0,
    },
    lineColor: {
      type: String,
      default: '',
    },
    lineWidth: {
      type: Number,
      default: 100,
    },
  });

  const emits = defineEmits(['change']);
  const distance = ref(0);
  const unit = 750 / props.list.length;
  const gap = (unit - props.lineWidth) / 2;
  const minDx = gap;
  const maxDx = (props.list.length - 1) * unit + gap;
  let lockDx = false;
  let dx = 0;

  const changeTab = (index: number) => {
    if (distance.value == props.list[index].distance) return;
    lockDx = true;
    emits('change', index);
  };

  const setDx = (offset: number) => {
    if (lockDx) return;
    dx = (props.list[props.current].distance as number) + (offset / 380) * unit;
    if (dx < minDx || dx > maxDx) return;
    distance.value = dx;
  };

  const unlockDx = () => (lockDx = false);

  watch(
    () => props.current,
    () => {
      distance.value = props.list[props.current].distance as number;
    }
  );

  defineExpose({
    setDx,
    unlockDx,
  });

  props.list.forEach((item, index) => {
    item.distance = gap + index * unit;
  });

  if (props.list[props.current]) {
    distance.value = props.list[props.current].distance as number;
  } else {
    changeTab(0);
    setTimeout(() => {
      unlockDx();
    }, 200);
  }
  props.list[props.current] ? (distance.value = props.list[props.current].distance as number) : changeTab(0);
</script>

<style lang="scss" scoped>
  .nav-box {
    display: flex;
    align-items: center;
    font-size: 30rpx;
    position: relative;

    .nav-item {
      width: 50%;
      display: flex;
      align-items: center;
      justify-content: center;

      .nav-text {
        position: relative;
        text-align: center;
        padding-bottom: 25rpx;
      }

      .nav-text-active {
        // color: $themeColor;
      }
    }

    .nav-line {
      position: absolute;
      width: v-bind("lineWidth + 'rpx'");
      bottom: 0;
      height: 6rpx;
      background: v-bind(lineColor);
      border-radius: 10rpx;
    }

    .nav-line-transition {
      transition: 0.3s all linear;
    }

    .line-bg {
      background: $themeColor;
    }
  }
</style>
